const Webpack = require("webpack")
const WebpackDevServer = require('webpack-dev-server')
const webpackConfig = require("./webpack.config")
const config = require('./config/')
var express = require('express');
// 创建一个express实例
var app = express();

// 调用webpack并把配置传递过去
var compiler = Webpack(webpackConfig)
// 使用 webpack-dev-middleware 中间件，搭建服务器
var devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: config.publicPath,
    stats: {
        colors: true,
        chunks: false
    }
})

// 使用 webpack-hot-middleware 中间件，实现热加载
var hotMiddleware = require('webpack-hot-middleware')(compiler);

// 为了修改html文件也能实现热加载，使用webpack插件来监听html源文件改变事件
compiler.plugin('compilation', function (compilation) {
    compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
        // 发布事件
        hotMiddleware.publish({ action: 'reload' });
        cb();
    })
});


// 注册中间件
app.use(devMiddleware);
app.use(hotMiddleware);
// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())
// serve pure static assets
app.use(express.static('./static'))
// 监听 80 端口，开启服务器
app.listen(80, function (err) {
    if (err) {
        console.log(err);
        return;
    }
    console.log('Listening at http://localhost:80');
})

// var server = new WebpackDevServer(compiler, {
//     disableHostCheck: true,
//     publicPath: config.publicPath,
//     historyApiFallback: true,
//     stats: {
//         colors: true //显示不同的颜色区分打包的文件
//     },
//     proxy: { //代理服务器
//         '*': {
//             target: config.target,
//             changeOrigin: true
//         }
//     }
// })

// server.listen(80, (err) => {
//     if (err) {
//         console.log(err)
//         return
//     }
// })